# -*- coding: utf-8 -*-

import wsgiref.handlers
import sys
import os
import string
import codecs
import random
import re
import cgi
import datetime
import time
import math
import pickle
import logging
import Cookie
import urllib
import urllib2

from google.appengine.ext.webapp import template
from google.appengine.ext import webapp

webapp.template.register_template_library('customfilters')
webapp.template.register_template_library('smart_if')

from math import sqrt
from google.appengine.api import mail
from google.appengine.ext.webapp import template
from google.appengine.ext import webapp
from google.appengine.ext import search
from google.appengine.ext import db
from google.appengine.api import urlfetch
from google.appengine.api import memcache
from google.appengine.api import users
from google.appengine.ext.webapp.util import run_wsgi_app
from datetime import datetime
from google.appengine.api import images
from models import *
from utilities import *

from django.utils import simplejson

from feed import *
from paging import *

# Set to true if we want to have our webapp print stack traces, etc
_DEBUG = True

class BaseRequestHandler(webapp.RequestHandler):
  """Supplies a common template generation function.

  When you call generate(), we augment the template variables supplied with
  the variables present in this function.
  """
  def generate(self, template_name, template_values={}):
    values = {
      'request': self.request,
      'application_name': 'Webcuo',
    }
    values.update(template_values)
    directory = os.path.dirname(__file__)
    path = os.path.join(directory, os.path.join('templates', template_name))
    self.response.out.write(template.render(path, values, debug=_DEBUG))

class AddFeed(BaseRequestHandler):
  def get(self):
    template_values = {
    }
    self.generate('addfeed.html', template_values)

  def post(self):
    url = self.request.get("url")
    lang = self.request.get("lang")
    country = self.request.get("country")
    sourcename = self.request.get("sourcename")

    afeed = Feed(url = url, lang = lang, country = country, sourceName = sourcename)
    afeed.put()
    self.redirect('/')

class Index(BaseRequestHandler):
  def get(self, page = 1):

    itemsPerPage = 100
    queryitems = PagedQuery(Domain.all(), itemsPerPage)
    queryitems.order("-pubDate")
    items = queryitems.fetch_page(int(page))

    pagingLinks = PageLinks(int(page), queryitems.page_count(), "/page/", 30).get_links()

    template_values = {
      'items': items,
      'pagingLinks': pagingLinks,
    }
    self.generate('index.html', template_values)

class aDomain(BaseRequestHandler):
  def get(self, domain):

    template_values = {
      'domain': domain,
    }
    self.generate('domain.html', template_values)

def main():
  urlmap = [
            ('/', Index),
            ('/page/(.*)/', Index),
            ('/addfeed/', AddFeed),
            ('/addfeed', AddFeed),
            ('/readfeeds/', FeedManager),
            ('/(.*)', aDomain),
            ('/(.*)/', aDomain),
           ]

  application = webapp.WSGIApplication(urlmap, debug=_DEBUG)
  wsgiref.handlers.CGIHandler().run(application)

if __name__ == "__main__":
  main()

